package com.tim.helper;

import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import org.apache.dubbo.config.ApplicationConfig;
import org.apache.dubbo.config.ReferenceConfig;
import org.apache.dubbo.config.RegistryConfig;
import org.springframework.util.ReflectionUtils;

import java.lang.reflect.Method;

/**
 * 输出dubbo直调命令，末尾无分号
 *  https://cn.dubbo.apache.org/zh-cn/docsv2.7/user/references/telnet/
 *
 *  报无RetryPolicy时，引入对应curator
 *  <dependency>
 *     <groupId>org.apache.curator</groupId>
 *     <artifactId>curator-framework</artifactId>
 *     <version>2.12.0</version>
 * </dependency>
 */
public class DubboExecuteHelper {
    static String registry="";

    public static void main(String[] args) throws NoSuchMethodException {
        Class clz = DubboExecuteHelper.class;
        String methodName="";
        Object[] objs = new Object[]{};
        invokeDubbo(clz, methodName, objs);

    }

    public static <T> void invokeDubbo(Class<T> clz, String methodName, Object... objs) throws NoSuchMethodException {
        ApplicationConfig applicationConfig=new ApplicationConfig();
        applicationConfig.setName("ltlTest");

        RegistryConfig registryConfig=new RegistryConfig();
        registryConfig.setAddress(registry);

        ReferenceConfig<T> referenceConfig=new ReferenceConfig<>();
        referenceConfig.setApplication(applicationConfig);
        referenceConfig.setRegistry(registryConfig);
        referenceConfig.setInterface(clz);
//        referenceConfig.setVersion("");
//        referenceConfig.setGroup("");

        T provider = referenceConfig.get();
        Class[] clzs=null;
        if(objs!=null){
            clzs=new Class[objs.length];
            for (int i = 0; i < objs.length; i++) {
                clzs[i]=objs[i].getClass();
            }
        }
        Method method = clz.getMethod(methodName, clzs);
        Object result = ReflectionUtils.invokeMethod(method, provider, objs);
        System.out.println(JSONUtil.toJsonPrettyStr(JSON.toJSONString(result)));
    }
}
